<!-- 运输单 -->
<template>
  <basic-container>
    <avue-crud :option="option" :table-loading="loading" :data="data" :page.sync="page" v-model="form" ref="crud"
      @search-change="searchChange" @search-reset="searchReset" @current-change="currentChange"
      @size-change="sizeChange" @refresh-change="refreshChange" @on-load="onLoad">
      <template slot="menuLeft" slot-scope="{ size }">
        <el-button type="primary" :size="size" @click="exportExcel()">导出</el-button>
      </template>
      <template slot="abnormalSpelling" slot-scope="scope">
        <el-switch v-model="scope.row.abnormalSpelling" active-value="1" inactive-value="0" active-color="#13ce66"
          inactive-color="#ff4949" @change="changeAbnormalSpelling(scope.row)">
        </el-switch>
      </template>
      <template slot-scope="{ row }" slot="menu">
        <el-button type="text" size="mini" icon="el-icon-view" @click.stop="view(row)">详情</el-button>
        <el-button type="text" size="mini" icon="el-icon-edit"
          v-if="row.orderType === 'ZFO5' || row.orderType === 'ZFOB'" @click.stop="completion(row)">补全信息</el-button>
        <el-button type="text" size="mini" icon="el-icon-edit" v-if="
          row.transportStatus === 'orderReceived' ||
          row.transportStatus === 'loaded'
        " @click.stop="distribution(row)">修改运单</el-button>
        <el-button type="text" size="mini" icon="el-icon-edit" v-if="row.transportStatus === 'orderReceived'"
          @click.stop="edit(row)">到达提货点</el-button>
        <el-button type="text" size="mini" icon="el-icon-edit" v-if="row.transportStatus === 'loaded'"
          @click.stop="edit(row)">启运</el-button>
        <el-button type="text" size="mini" icon="el-icon-edit"
          v-if="row.transportStatus === 'arriveAtTheTransferStation'" @click.stop="edit(row)">到达中转站</el-button>
        <el-button type="text" size="mini" icon="el-icon-edit" v-if="row.transportStatus === 'shipped'"
          @click.stop="edit(row)">运达</el-button>
        <el-button type="text" size="mini" icon="el-icon-edit" v-if="
          row.transportStatus === 'arrived' &&
          (row.orderType === 'ZFO6' ||
            row.orderType === 'ZFOE' ||
            row.orderType === 'ZFOC') &&
          permission.tms_transportorder_unloading
        " @click.stop="edit(row)">卸货</el-button>
        <el-button type="text" size="mini" icon="el-icon-edit"
          v-if="row.transportStatus === 'arrived' && row.orderType !== 'ZFO6' && row.orderType !== 'ZFOE' && row.orderType !== 'ZFOC'"
          @click.stop="sign(row)">签收</el-button>
        <el-button type="text" size="mini" icon="el-icon-view" v-if="row.pushTag === '1'"
          @click.stop="transportationTrack(row)">运输轨迹</el-button>
        <el-button type="text" size="mini" icon="el-icon-close" v-if="
          row.transportStatus !== 'abolished' &&
          permission.tms_transportorder_toVoid
        " @click.stop="toVoid(row)">作废</el-button>
        <el-button type="text" size="mini" icon="el-icon-view" v-if="
          row.transportStatus === 'abolished' &&
          permission.tms_transportorder_viewToVoid
        " @click.stop="viewToVoid(row)">作废原因</el-button>
      </template>
    </avue-crud>
    <tranportDetail ref="tranportDetail" />
    <sign ref="sign" @refresh="refresh" />
    <assignWaybill ref="assignWaybill" @refresh="refresh" />
    <transportCompletionInfo ref="transportCompletionInfo" @refresh="refresh" />
    <tipsDialog ref="tipsDialog" />
  </basic-container>
</template>

<script>
import {
  getTransportList,
  waybillStatusChange,
  updateStart,
  transportToVoid,
} from "@/api/transportation/demandorder";
import tranportDetail from "./components/tranportDetail";
import sign from "./components/sign";
import assignWaybill from "./components/assignWaybill";
import transportCompletionInfo from "./components/transportCompletionInfo";
import { mapGetters } from "vuex";
import tipsDialog from "./components/tipsDialog";
import { getToken } from "@/util/auth";
import { serialize } from "@/util/util";
import { getBeforeCurrentDateDays } from "@/util/date";

export default {
  data() {
    return {
      form: {},
      query: {},
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      option: {
        height: "auto",
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchLabelWidth: 100,
        searchSpan: 6,
        searchMenuSpan: 4,
        border: true,
        index: true,
        addBtn: false,
        editBtn: false,
        delBtn: false,
        labelWidth: "180",
        menuWidth: "200",
        column: [
          {
            label: "运输单号",
            prop: "transportNo",
            width: 115,
            search: true,
          },
          {
            label: "货运订单",
            prop: "orderNo",
            width: 100,
            search: true,
          },
          {
            label: "货运订单类型",
            prop: "orderType",
            type: "select",
            multiple: true,
            searchLabelWidth: "100",
            props: {
              label: "value",
              value: "key",
            },
            search: true,
            width: 100,
            dicUrl: `/api/blade-tms/common/SelectEnum?name=torType`,
            editDisplay: false,
            addDisplay: false,
          },
          {
            label: "交货单",
            prop: "deliverNo",
            width: 100,
            search: true,
          },
          {
            label: "订单号",
            width: 100,
            prop: "orderNumber",
          },
          {
            label: "运单状态",
            width: 100,
            prop: "transportStatus",
            type: "select",
            props: {
              label: "value",
              value: "key",
            },
            // search: true,
            dicUrl: `/api/blade-tms/common/SelectEnum?name=waybillStatus`,
          },
          {
            label: "承运商",
            width: 120,
            prop: "carrierName",
            search: true,
          },
          {
            label: "司机",
            prop: "driverName",
            width: 100,
            search: true,
          },
          {
            label: "押运员",
            width: 100,
            prop: "supercargoName",
          },
          {
            label: "车牌号",
            prop: "carNo",
            width: 100,
            search: true,
          },
          {
            label: "挂车号",
            prop: "bindCarNo",
            width: 100,
            // search: true,
          },
          {
            label: "罐箱号",
            prop: "containerNo",
            width: 100,
            search: true,
          },
          {
            label: "铅封号",
            width: 100,
            prop: "leadSealNumber",
          },
          {
            label: "提单号",
            width: 100,
            prop: "billOfLadingNumber",
          },
          {
            label: "客户名称",
            width: 100,
            prop: "customerName",
            search: true,
          },
          {
            label: "国际贸易条款",
            width: 100,
            prop: "tradeTerms",
          },
          {
            label: "条款附加信息",
            width: 100,
            prop: "tradeTermsItem",
          },
          {
            label: "源位置街道",
            width: 150,
            prop: "sourceLocationStreet",
          },
          {
            label: "目标位置街道",
            width: 150,
            prop: "destinationStreet",
          },
          {
            label: "物料信息",
            width: 100,
            prop: "materialInformation",
          },
          {
            label: "合同公司",
            width: 100,
            prop: "contractCompany",
          },
          {
            label: "计划提货日期",
            width: 100,
            prop: "planGetGoodsDateStart",
          },
          {
            label: "计划收货日期",
            width: 100,
            prop: "planGetGoodsDateEnd",
          },
          {
            label: "预计到厂时间",
            width: 100,
            prop: "expectedArrivalTimeAtTheFactory",
          },
          {
            label: "创建时间",
            width: 100,
            prop: "createTime",
          },
          {
            label: "异常拼车",
            width: 100,
            prop: "abnormalSpelling",
            slot: true,
          },
          {
            label: "计划提货日期",
            type: "datetime",
            prop: "planGetGoodsDate",
            search: true,
            searchLabelWidth: "100",
            searchRange: true,
            hide: true,
            showColumn: false,
            searchValue: this.getInitDate(),
            // defaultTime: ["00:00:00", "23:59:59"],
            format: "yyyy-MM-dd",
            valueFormat: "yyyy-MM-dd",
            startPlaceholder: "请选择开始日期",
            endPlaceholder: "请选择结束日期",
          },
          {
            label: "计划收货日期",
            type: "datetime",
            prop: "plannedDeliveryDate",
            // search: true,
            searchLabelWidth: "100",
            searchRange: true,
            hide: true,
            showColumn: false,
            defaultTime: ["00:00:00", "23:59:59"],
            format: "yyyy-MM-dd HH:mm:ss",
            valueFormat: "yyyy-MM-dd HH:mm:ss",
            startPlaceholder: "请选择开始日期",
            endPlaceholder: "请选择结束日期",
          },
        ],
      },
      data: [],
    };
  },
  components: {
    tranportDetail,
    sign,
    assignWaybill,
    transportCompletionInfo,
    tipsDialog,
  },
  computed: {
    ...mapGetters(["permission"]),
  },
  methods: {
    getInitDate() {
      let startDate = [getBeforeCurrentDateDays(-1), getBeforeCurrentDateDays(2)];
      return startDate;
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      if (!params.planGetGoodsDate) {
        this.$message('请选择计划提货日期');
        done();
        return;
      }
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    refresh() {
      this.onLoad(this.page);
    },
    onLoad(page, params = {}) {
      let initDate = this.getInitDate();
      let query = Object.assign(params, this.query);
      if (query.planGetGoodsDate) {
        query = {
          ...query,
          planGetGoodsDateStart: query.planGetGoodsDate
            ? query.planGetGoodsDate[0] + " 00:00:00"
            : "",
          planGetGoodsDateEnd: query.planGetGoodsDate
            ? query.planGetGoodsDate[1] + " 00:00:00"
            : "",
        };
        delete query.planGetGoodsDate;
      } else {
        query = {
          ...query,
          planGetGoodsDateStart: initDate[0] + " 00:00:00",
          planGetGoodsDateEnd: initDate[1] + " 00:00:00",
        }
      }
      if (query.plannedDeliveryDate) {
        query = {
          ...query,
          plannedHarvestDateStart: query.plannedDeliveryDate
            ? query.plannedDeliveryDate[0]
            : "",
          plannedHarvestDateEnd: query.plannedDeliveryDate
            ? query.plannedDeliveryDate[1]
            : "",
        };
        delete query.plannedDeliveryDate;
      }
      if (query.orderType && typeof query.orderType === "object") {
        query = {
          ...query,
          freightOrderTypes: query.orderType.join(","),
        };
        delete query.orderType;
      }
      this.loading = true;
      getTransportList(page.currentPage, page.pageSize, query).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.$nextTick(() => {
          this.$refs.crud.$refs.table.doLayout();
        });
      });
    },
    view(row) {
      this.$refs.tranportDetail.open(row.id, row.orderType);
    },
    edit(row) {
      let updateData = {
        id: row.id,
        operating: "",
      };
      switch (row.transportStatus) {
        case "orderReceived":
          updateData.operating = "到达提货点";
          break;
        case "loaded":
          updateData.operating = "启运";
          break;
        case "arriveAtTheTransferStation":
          updateData.operating = "到达中转站";
          break;
        case "shipped":
          updateData.operating = "运达";
          break;
        case "arrived":
          updateData.operating = "卸货";
          break;
      }
      this.$confirm(`是否确定${updateData.operating}?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          waybillStatusChange(updateData).then(
            () => {
              this.onLoad(this.page);
              this.$message({
                type: "success",
                message: "操作成功!",
              });
            },
            (error) => {
              window.console.log(error);
            }
          );
        })
        .catch(() => { });
    },
    sign(row) {
      this.$refs.sign.open(row.id);
    },
    //分配运单
    distribution(row) {
      this.$refs.assignWaybill.open(
        row.demandId,
        row.carrierNo,
        row.orderType,
        "edit",
        row.id,
        row.transportNo
      );
    },
    //运输轨迹
    transportationTrack(row) {
      this.$router.push({
        path: "/transportation/components/transportationTrack",
        query: {
          transportNo: row.transportNo,
        },
      });
    },
    //作废
    toVoid(row) {
      this.$prompt("请输入作废原因", "作废原因", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputPattern: /\S/,
        inputErrorMessage: "请输入作废原因",
      })
        .then(({ value }) => {
          transportToVoid({ id: row.id, reasonForVoiding: value }).then(
            () => {
              this.onLoad(this.page);
              this.$message({
                type: "success",
                message: "操作成功!",
              });
            },
            (error) => {
              window.console.log(error);
            }
          );
        })
        .catch(() => { });
    },
    //查看作废原因
    viewToVoid(row) {
      this.$refs.tipsDialog.open("作废原因", row.reasonForVoiding);
    },
    //补全信息
    completion(row) {
      this.$refs.transportCompletionInfo.open(row.id);
    },
    //异常拼车
    changeAbnormalSpelling(row) {
      updateStart(row.id, row.abnormalSpelling).then(
        () => {
          this.onLoad(this.page);
          // this.$message({
          //   type: "success",
          //   message: "操作成功!",
          // });
        },
        (error) => {
          window.console.log(error);
        }
      );
      updateStart;
    },
    //导出
    exportExcel() {
      let query = this.$refs.crud.$refs.headerSearch.searchForm;
      if (query.planGetGoodsDate && query.planGetGoodsDate.length > 0) {
        query = {
          ...query,
          planGetGoodsDateStart: query.planGetGoodsDate
            ? query.planGetGoodsDate[0]
            : "",
          planGetGoodsDateEnd: query.planGetGoodsDate
            ? query.planGetGoodsDate[1]
            : "",
        };
      }
      if (query.plannedDeliveryDate && query.plannedDeliveryDate.length > 0) {
        query = {
          ...query,
          plannedHarvestDateStart: query.plannedDeliveryDate
            ? query.plannedDeliveryDate[0]
            : "",
          plannedHarvestDateEnd: query.plannedDeliveryDate
            ? query.plannedDeliveryDate[1]
            : "",
        };
      }
      if (query.orderType && typeof query.orderType === "object") {
        query = {
          ...query,
          freightOrderTypes: query.orderType.join(","),
        };
      }
      delete query.planGetGoodsDate;
      delete query.plannedDeliveryDate;
      delete query.orderType;
      var url = `/api/blade-tms/transportorder/TransportList/download?Blade-Auth=bearer ${getToken()}&${serialize(
        query
      )}`;
      this.downFile(url);
    },
  },
};
</script>

<style></style>
